package com.kaibes.module.nacos;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.annotation.NacosProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.EnableNacos;

@Configuration
@EnableNacos(globalProperties = @NacosProperties(
        serverAddr = "${spring.cloud.nacos.server-addr:${spring.cloud.nacos.discovery.server-addr}}", 
        username = "${spring.cloud.nacos.username:${spring.cloud.nacos.discovery.username:nacos}}", 
        password = "${spring.cloud.nacos.password:${spring.cloud.nacos.discovery.password:nacos}}",
        namespace = "${spring.cloud.nacos.namespace:${spring.cloud.nacos.discovery.namespace:public}}", 
        enableRemoteSyncConfig = "true", maxRetry = "5", configRetryTime = "4000", configLongPollTimeout = "26000"))
public class NacosConfig implements InitializingBean {
    
    @Autowired(required = false)
    private List<NacosEventListener> eventList;
    @NacosInjected
    private NamingService naming;
    
	@Override
	public void afterPropertiesSet() throws Exception {
		if (eventList == null)
            return;
        
        for (NacosEventListener nacosEventListener : eventList) {
            try {
                naming.subscribe(nacosEventListener.getName(), nacosEventListener.getGroup(), nacosEventListener::onEvent);
            } catch (NacosException e) {
                e.printStackTrace();
            }
        }
	}
    
}
